/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package banksystem;

/**
 *
 * @author conra_000
 */
public class CertificateOfDeposit extends Account{
	int mPeriodInMinutes;
	long mBeginDate;
	long mCalcFromDate;
	long mMatureDate;
	double mMinutePercentageRate;
	
	CDPackage mPackage;
	
	
	public CertificateOfDeposit(long accountID, CDPackage pac) {
		super(accountID);
		mPackage = pac;
		mBeginDate = super.getID();
		mCalcFromDate = mBeginDate;
		mPeriodInMinutes = mPackage.getPeriod();
		mMatureDate = super.getID() + (mPackage.getPeriod() * 1000 * 60);
		
		mMinutePercentageRate = mPackage.getInterestRate();
	}
	
	public CDPackage getPackage() {
		return mPackage;
	}

	@Override
	public boolean Withdraw(double amount, TransferTransaction transfer) {
		updateBalance();
		
		//deduct penalty if the CD is not matured
		if(!this.isMatured()) {
			double penaltyAmount = getPenaltyAmount(amount);
			super.Penalty(penaltyAmount);
		} 
		
		return super.Withdraw(amount, transfer);
	}

	@Override
	public boolean Withdraw(double amount) {
		updateBalance();
		
		//deduct penalty if the CD is not matured
		if(!this.isMatured()) {
			double penaltyAmount = getPenaltyAmount(amount);
			super.Penalty(penaltyAmount);
		} 

		return super.Withdraw(amount);
	}

	@Override
	public double getBalance() {
		updateBalance();
		return super.getBalance();
	}
	
	public double getPenaltyAmount(double withdrawSize) {
		return Math.round(((double) mPackage.getPenalty() + (.03 * withdrawSize))*100.0) / 100.0;
	}

	@Override
	public boolean Deposit(double amount) {
		return false;
	}

	@Override
	public boolean Deposit(double amount, TransferTransaction transfer) {
		return false;
	}
	
	public boolean isMatured() {
		long currentDate = System.currentTimeMillis();
		if(currentDate > mMatureDate) {
			return true;
		} else {
			return false;
		}
	}
	
	private void updateBalance() {
		long currentDate = System.currentTimeMillis();
		//if there is more maturing to be done
		if(mCalcFromDate < mMatureDate) {
			//if the current time is after complete maturity, use maturity date as current date
			if(currentDate > mMatureDate) {
				currentDate = mMatureDate;
			}
			
			double minutesSinceUpdate = (double) (currentDate-mCalcFromDate)/(60*1000);
			
			double newBalance = (double) super.getBalance() * (double) Math.pow(2.718281828, (double) mMinutePercentageRate * (double) minutesSinceUpdate);
			changeBalance(newBalance);
			mCalcFromDate = currentDate;
		}
	}

}
